import React from 'react';
import { isEmpty } from 'lodash';

import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { Synergy } from '../../document/components/Portal/Portal';


import { Row, Col, Tabs, Button, Modal, Icon, Table, Menu, Dropdown } from 'antd';

const MenuItem = Menu.Item;
const warning = Modal.warning;

import {
  WeaReqTop,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaRichText,
  WeaInput,
  WeaUpload,
  WeaNewScroll,
  WeaAuth,
  WeaFormItem,
  WeaDialog,
  WeaLocaleProvider,
  WeaCheckbox,
  WeaHelpfulTip,
  WeaSelect,
} from 'ecCom';

import { WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import * as Util from '../util/transf';

import '../style/detail.less';

import BackToE8 from './Detail/BackToE8';

const getLabel = WeaLocaleProvider.getLabel;
import DocDetailConstant from '../util/DocDetailConstant';
import CustomButton from './FileView/CustomButton';
import DataListItem from './DetailForm/DataListItem';

@inject('docDetailFormStore')
@observer
class DetailForm extends React.Component {
  constructor(props) {
    super(props);
    const idReg = window.location.search.match(/(\?|\&)id=\d+/g);
    const secidReg = window.location.search.match(/(\?|\&)secid=\d+/g);
    const officeReg = window.location.search.match(/(\?|\&)isOffice=\d+/g);
    this.isIE = !!window.ActiveXObject || 'ActiveXObject' in window;
    // 获取是否是正文，获取文件名称
    let requestDocReg = window.location.search.match(/(\?|\&)requestDoc=\d+/g);
    requestDocReg = requestDocReg && requestDocReg.length === 1 ? requestDocReg[0].split('=')[1] : '';
    let documentTitleField = '';
    if (requestDocReg === '1' && window.location.href.indexOf('documentTitleField=') > 0) {
	    let documentTitleFieldHref = window.location.href.substring(window.location.href.indexOf('documentTitleField=') + 19);
	    if (documentTitleFieldHref.indexOf('&') > 0) documentTitleFieldHref = documentTitleFieldHref.substring(0, documentTitleFieldHref.indexOf('&'));
	    documentTitleField = documentTitleFieldHref;
		  if (documentTitleField === '-3') documentTitleField = '-1';
    }

    let requestDocSubject = '';
    if (requestDocReg === '1') {
      requestDocSubject = window.parent.WfForm.getFieldValue(`field${documentTitleField}`);
      if (!requestDocSubject) {
        requestDocSubject = window.parent.WfForm.getFieldValue('field-1');
      }
    }
    const officeTypeReg = window.location.search.match(/(\?|\&)officeType=\.\w+/g);
    this.state = {
      id: idReg && idReg.length === 1 ? idReg[0].split('=')[1] : '',
      secid: secidReg && secidReg.length === 1 ? secidReg[0].split('=')[1] : '',
      isOffice: officeReg && officeReg.length === 1 ? officeReg[0].split('=')[1] : '',
      officeType: officeTypeReg && officeTypeReg.length === 1 ? officeTypeReg[0].split('=')[1] : '',
      status: '',
      richHeight: 0,

      requestDoc: requestDocReg,
      requestDocSubject,

      selectedRowKeys: [],
      selectedRows: [],
      richFileList: [],
      imgList: [],
      imgUploadStatus: '',
      versionVisible: false,
      shareAddVisible: false,
      editionRecord: {},

      list: [],

      richTextUploadStatus: false,
      showWarm: false,
      isIE: this.isIE,
    };
    this.onTabsChange = this.onTabsChange.bind(this);
    this.onToolsChange = this.onToolsChange.bind(this);
    this.doShareAddDelete = this.doShareAddDelete.bind(this);
    window.__onRightMenuClick = this.onRightMenuClick.bind(this);
    window.doOdocSubmit = this.onRightMenuClick.bind(this);
  }
  componentDidMount() {
    // 一些初始化请求
    const { docDetailFormStore } = this.props;
    const { id, secid, officeType, requestDoc, requestDocSubject, docsubjectReg } = this.state;


    const richHeight = document.documentElement.clientHeight -
      $('.wea-new-top-req-content').offset().top - 137;

    this.setState({ richHeight });
    docDetailFormStore.setDatas({ isAdd: !!secid });
    docDetailFormStore.getEditSet({ id, secid });
    docDetailFormStore.getProperty({ id, secid, officeType });
    requestDoc === '1'
    ? docDetailFormStore.setBasic({ docSubject: requestDocSubject })
    : docDetailFormStore.getBasic({ id, secid, officeType });
    if (id) {
      docDetailFormStore.getHtmlContent({ id, secid });
      docDetailFormStore.getFileList({ id, secid });
      docDetailFormStore.searchShare({ id });
      docDetailFormStore.canShareAddEdit({ id });
    }
    $(window).resize(() => {
      this._reactInternalInstance !== undefined &&
        this.state.status === 'ready' && !this.refs.doc_add.state.maximize && this.resetHeight();
    });
    window.doOdocSubmit = function (para) {
      docDetailFormStore.doSubmit(para);
    };
    // if (window.location.pathname.indexOf('/spa/document/') >= 0) {
    //   document.title = this.state.id ? getLabel(386301,"文档编辑") : getLabel(1986,'新建文档');
    // }
    window.onbeforeunload = function (e) {
      e = e || window.event;
      if (e) {
        e.returnValue = '关闭提示';
      }
      return '关闭提示';
    };
  }
  componentDidUpdate() {
    this.state.status === 'ready' && this.refs.doc_add
      && !this.refs.doc_add.state.maximize && this.resetHeight();
  }
  componentWillUnmount() {
      const { docDetailFormStore } = this.props,
{ isClickSubmit } = docDetailFormStore;
      const { id } = this.state;
      if (!isClickSubmit) {
        docDetailFormStore.docfileCheckIn(id);
      }
      window.onbeforeunload = undefined;
    // 组件卸载时一般清理一些状态
  }
  resetHeight() {
    const richHeight = document.documentElement.clientHeight
      - $('.wea-new-top-req-content').offset().top - 95
      - ($('.wea-doc-detail-content-inner .wea-rich-text').find('.cke_top').height() + 9);
    $('.wea-doc-detail-content-inner .wea-rich-text').find('.cke_contents').height(richHeight);
  }
  // tab
  getTabPane() {
    const { tabKey } = this.props.docDetailFormStore;
    const { richFileList, id } = this.state;
    const tabInfo = [
      {
        key: '0',
        value: getLabel(18332, '正文内容'),
      },
      {
        key: '1',
        value: getLabel(33197, '文档属性'),
      },
      {
        key: '2',
        value: <span>{getLabel(31208, '文档附件')}{richFileList.length > 0 && tabKey === '0'
          && <span style={{ color: '#f00', fontSize: 11 }}>
            {` (${richFileList.length})`}</span>}</span>,
      },
    ];
    id && tabInfo.push({
      key: '3',
      value: getLabel(1985, '文档共享'),
    });
    return tabInfo.map(data => <Tabs.TabPane ecId={`${this && this.props && this.props.ecId || ''}_undefined@s0j1b4@${data.key}`} tab={data.value} key={data.key} />);
  }
  onTabsChange(key) {
    const { docDetailFormStore } = this.props;
    docDetailFormStore.setTabKey(key);
    key === '2' && this.setState({ richFileList: [] });
  }
  onChangeList = (ids, l) => this.setState({ list: l })
  onUploadingList = (s) => {
    const { list } = this.state;
    const { docDetailFormStore } = this.props;
    const { loading } = docDetailFormStore;
    if (s === 'uploaded' && list.length === 1 && window.changeOfficeFile) {
      window.changeOfficeFile(list[0].fileid, list[0].fileExtendName);
       docDetailFormStore.doLoading(false);
    } else if (s === 'error') {
       docDetailFormStore.doLoading(false);
    } else if (!loading) {
      docDetailFormStore.doLoading(true);
    }
  }

  // 右键菜单
  getButtons() {
  	const { docDetailFormStore } = this.props;
    const { rightMenus, loading } = docDetailFormStore;
    const { richTextUploadStatus } = this.state;
    const btnArr = [];
    toJS(rightMenus).forEach((btn) => {
      if (btn.isTop === '1') {
      	  if (btn.type === 'BTN_OPEN_LOCAL_FILE') {
	        btnArr.push(<WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@dv7zh6@${btn.type}`}
  style={{ paddingTop: 0 }}
  title={getLabel(16381, '打开本地文件')}
  uploadUrl="/api/doc/upload/uploadFile"
  category="string"
  multiSelection={false}
  maxFilesNumber={1}
  maxUploadSize={btn.customData.maxUploadSize}
  limitType={btn.customData.limitType}
  onChange={this.onChangeList}
  onUploading={this.onUploadingList}
	        >
	          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@u4sy52@${btn.menuName}`} disabled={loading || richTextUploadStatus === 'uploading'} type="primary">{btn.menuName}</Button>
	        </WeaUpload>);
	      } else {
          btnArr.push(<CustomButton
            ecId={`${this && this.props && this.props.ecId || ''}_Button@udocon@${btn.menuName}`}
            disabled={loading || richTextUploadStatus === 'uploading'}
            type="primary"
            btn={btn}
            onRightMenuClick={this.onRightMenuClick}
          >
            {btn.menuName}
          </CustomButton>);
	      }
      }
    });
    return btnArr;
  }
  getRightMenu() {
  	const { docDetailFormStore } = this.props;
    const { rightMenus, loading } = docDetailFormStore;
    const btnArr = [];
    const { list, isIE } = this.state;
    toJS(rightMenus).forEach((btn) => {
	      let com = {
	        key: btn.type,
	        icon: <i className={btn.menuIcon} />,
	        content: btn.menuName,
	        disabled: loading,
	        onClick: this.onRightMenuClick,
	      };
	      if (btn.type === 'BTN_OPEN_LOCAL_FILE') {
	        com.content = (
	          <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@q6dyt4@${btn.type}`}
  className="replace-file"
  style={{ paddingTop: 0 }}
  title={getLabel(16381, '打开本地文件')}
  uploadUrl="/api/doc/upload/uploadFile"
  category="string"
  multiSelection={false}
  maxFilesNumber={1}
  maxUploadSize={btn.customData.maxUploadSize}
  limitType={btn.customData.limitType}
  onChange={this.onChangeList}
  onUploading={this.onUploadingList}
	          >
		          <div style={{ paddingLeft: isIE ? 42 : '' }}>{btn.menuName}</div>
		        </WeaUpload>);
	      }

	       btnArr.push(com);
    });
    // this.forceUpdate();
    return btnArr;
  }
  cancelWarning = () => {
    this.setState({ showWarm: false });
  }
  submitWarning = (content) => {
    warning({
      title: getLabel(127354, '警告'),
      content,
      onOk: this.cancelWarning,
      onCancel: this.cancelWarning,
    });
  }

  onRightMenuClick = (key, isflowdoc, flowdocObj) => {
    const { docDetailFormStore } = this.props;
    const { form, fileList, docSubject, doccontent, canShowBJCA } = docDetailFormStore;
    const { id, secid, isOffice } = this.state;
    const fileids = fileList.map(file => file.fileid);
    let that = this;
    if (key === 'BTN_OPEN_LOCAL_FILE') {

    } else if (key === 'BTN_SUBMIT' || key === 'BTN_DRAFT') {
      if (window.__useWpsView && !window.__wpsSaved) {
      	docDetailFormStore.doLoading(true);
      	window.sendSaveMsg(key);
      	return;
      }

      window.onbeforeunload = undefined;
      docDetailFormStore.isClickSubmit = true;
      let bodyStyle = '';
      let divDocContent = doccontent;

      if (this.refs && this.refs.doc_add && this.refs.doc_add.getData) {
      	divDocContent = this.refs.doc_add.getData();
      }
      const submitParams = {
        operate: key.replace(/\w+\_/g, '').toLocaleLowerCase(),
        docSubject,
        doccontent: divDocContent.replace(
          /<link\s?[^>]+\/spa\/document\/content\.css{1}[^>]+\s?\/>/g, () => '',
        ),
        fileids: `${fileids}`,
        ...form.getFormParams(),
        id,
        isOffice,
      };
      if (isflowdoc === 1 || this.validateParams(submitParams)) {
        docDetailFormStore.doLoading(true);
        docDetailFormStore.isExists({
          secid,
          docid: id,
          docSubject,
        }, (data) => {
          docDetailFormStore.doLoading(false);
          if (data.status === 1 || isflowdoc === 1) {
            if (isOffice) {
              if (isflowdoc === 1) {
	              const obj = flowdocObj;
	              docDetailFormStore.doSubmit({ ...submitParams, ...obj, flowdocObj, isflowdoc });
              } else {
                const obj = window.saveDocument(docSubject);
	              if (obj && obj.off_status === 1) {
	                docDetailFormStore.doSubmit({ ...submitParams, ...obj });
	              } else if (!canShowBJCA) {
                  if (isOffice) {
                    that.setState({ showWarm: true });
                  }
                  this.submitWarning(obj.msg || `office ${getLabel(84544, '保存失败！')}`);
                }
              }
            } else {
              docDetailFormStore.doSubmit({ ...submitParams });
            }
          } else {
          	if (isOffice) {
	        	  that.setState({ showWarm: true });
            }
            this.submitWarning(data.msg);
          }
        });
      } else {
      	docDetailFormStore.doLoading(false);
        if (isOffice) {
        	that.setState({ showWarm: true });
        }
        this.submitWarning(getLabel(385868, '您有必填项未填写！'));
      }
    } else {
      // BTN_CREATE_DOC_HTML
      // BTN_CREATE_DOC_DOC
      // BTN_CREATE_DOC_DOCX
      // BTN_CREATE_DOC_XLS
      // BTN_CREATE_DOC_XLSX
      // BTN_CREATE_DOC_WPS
      let officeType = key.replace('BTN_CREATE_DOC_', '').toLocaleLowerCase();
      if (officeType === 'html') {
        officeType = '';
      } else {
        officeType = `&isOffice=1&officeType=.${officeType}`;
      }

      if (isflowdoc === 1) {
      } else {
        window.location.href = `${window.location.pathname}?secid=${secid}`
        + `&isEdit=1${officeType}${window.__moudleParams}#/main/document/edit`;
      }
      window.onbeforeunload = undefined;
    }
  }
  validateParams(params) {
    const { docDetailFormStore } = this.props;
    let hasDoneMust = true;
    let goProp = false;
    if (!params.docSubject) hasDoneMust = false;
    toJS(docDetailFormStore.property).forEach((prop) => {
      if (prop.paramForm.show
        && prop.paramForm.viewAttr === 3
        && !params[prop.paramForm.domkey[0]]) {
        hasDoneMust = false;
        goProp = true;
      }
    });
    !hasDoneMust && goProp && docDetailFormStore.setTabKey('1');
    return hasDoneMust;
  }
  // 富文本
  onChangeExtendsConfig = (ids, list) => {
    const { docDetailFormStore } = this.props;
    const { id } = this.state;
    this.setState({ imgList: list });
    this.refs.doc_add.insertHTML(Util.transfStr('Upload', ids, list, 'image', true));
    this.refs.doc_add.focus('last');
    docDetailFormStore.saveFilesTmp({ docid: id, fileid: `${ids}` });
  }
  onUploadingExtendsConfig = (s) => {
    const { imgList } = this.state;
    this.setState({ imgUploadStatus: s, imgList: s === 'uploading' ? [] : imgList });
  }
  getExtentsConfig() {
    const { imgUploadStatus, imgList } = this.state;
    return [{
      name: 'Component',
      show: (
        <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@5ysepr@uploadRichTextImg`}
          datas={imgUploadStatus === 'uploaded' ? [] : imgList}
          uploadUrl="/api/doc/upload/uploadFile"
          category="-1"
          title={getLabel(20001, '上传图片')}
          limitType="jpg,jpeg,gif,bmp,png"
          onChange={this.onChangeExtendsConfig}
          onUploading={this.onUploadingExtendsConfig}
        >
          <span className="cke_button_icon cke_button__image_icon" />
        </WeaUpload>
      ),
    }];
  }
  onToolsChange(name = '', ids = '', list = [], type = '') {
    if (name === 'Upload' && type === 'file') {
      const { docDetailFormStore } = this.props;
      let fileList = toJS(docDetailFormStore.fileList);
      const { id } = this.state;
      docDetailFormStore.updateFileList(fileList.concat(list));
      docDetailFormStore.saveFilesTmp({ docid: id, fileid: `${ids}` });
      this.setState({ richFileList: list });
      // docDetailFormStore.setTabKey('2');
      return ' ';
    }
    return Util.transfStr(name, ids, list, type, name === 'Upload' && type === 'image');
  }

  // 文档属性
  getAttr() {
    const { docDetailFormStore } = this.props,
    property = toJS(docDetailFormStore.property),
      { form } = docDetailFormStore;
    if (!form.isFormInit) { return null; }
    let items = property.map((item) => {
      const { paramForm, value, column = 1, label } = item;
      const { show, conditionType } = paramForm;
      if (!show) {
        return null;
      }
      let field = { ...paramForm,
        label,
        labelcol: 6 / column,
        fieldcol: 24 - 10 / column,
                    underline: !conditionType,
        hasBorder: !!conditionType };
      if (!conditionType) {
        field.conditionType = 'CUSTOM';
        field.otherCom = (
          <span dangerouslySetInnerHTML={{ __html: value }} />
        );
      } else if (conditionType == 'TEXTAREA') {
        field.defaultValue = field.defaultValue.replace(/<br>/g, '\n');
      } else if (conditionType == 'CUSTOM' && (paramForm.customType == 'INPUT_INT' || paramForm.customType == 'INPUT_FLOAT')) {
        field.conditionType = 'INPUT';
        field.otherParams = {
          ...field.otherParams,
          inputType: 'FORM',
          format: { numberType: 0 },
          qfws: paramForm.customType == 'INPUT_INT' ? 0 : paramForm.floatPoint,
          detailtype: paramForm.customType == 'INPUT_INT' ? 2 : 3,
        };
      }
      if (field.domkey[0] === 'selectedPubMouldId') {
        field.onChange = docDetailFormStore.changeSelectedPubMouldId;
      } else if (field.domkey[0] === 'seccategory') {
        field.onChange = docDetailFormStore.changeSecCategory;
      } else if (field.domkey[0] === 'docPublishType') {
        field.onChange = docDetailFormStore.changeDocPublishType;
      } else if (field.domkey[0] === 'secretLevel') {
      	field.onChange = docDetailFormStore.changeSecretLevel;
      }
      return (
        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@xl2q1f@${field.domkey[0]}`} span={12 * column}>
          {DocDetailConstant.createFormItem(field, form)}
        </Col>
      );
    }).filter(item => !!item);
    return (
      <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@ler33i`} className="wea-doc-detail-content-inner-attr wea-search-group">
        {items}
      </Row>
    );
  }
  // 文档附件
  onChangeFileList = (ids, list) => {
    const { id } = this.state;
    const { docDetailFormStore } = this.props;
    docDetailFormStore.updateFileList(list);
    docDetailFormStore.saveFilesTmp({ docid: id, fileid: `${ids}` });
  }
  onUploadingFileList = (s) => {
    const { docDetailFormStore } = this.props;
    docDetailFormStore.doLoading(s === 'uploading');
  }
  getFileUpload() {
    const { docDetailFormStore } = this.props;
    let fileList = toJS(docDetailFormStore.fileList),
      footConfig = toJS(docDetailFormStore.footConfig);
    const { selectedRowKeys, id } = this.state;
    const upload = footConfig.filter(conf => conf.name === 'Upload') || [];
    const maxUploadSize = !isEmpty(upload) ? upload[0].maxUploadSize : '';
    return (
      <div className="wea-table-edit">
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@n0k0y3`} className="wea-table-edit-title" >
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@6uvrca`}>
            {getLabel(21704, '附件列表')}
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@x4euwq`}
              type="primary"
              disabled={!`${selectedRowKeys}`}
              style={{ width: 22 }}
              title={getLabel(91, '删除')}
              size="small"
              onClick={this.doDelete}
            ><span className="icon-coms-form-delete-hot" /></Button>
            {
              upload.length === 1 && maxUploadSize != '0' ?
              <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@1prpei`}
                {...upload[0]}
                datas={fileList}
                onChange={this.onChangeFileList}
                onUploading={this.onUploadingFileList}
              >
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@96g0sd`}
                  style={{ width: 22 }}
                  type="primary"
                  title={`${getLabel(17616, '附件上传')}(${getLabel(385926, '最大{max}M/个').replace('{max}', upload[0].maxUploadSize)})`}
                  size="small"
                ><span className="icon-coms-Add-to-hot" /></Button>
              </WeaUpload> : <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kvahwm`}
                style={{ width: 22 }}
                type="primary"
                title={getLabel(1421, '新增')}
                size="small"
                disabled={true}
              ><span className="icon-coms-Add-to-hot" /></Button>
            }
          </Col>
        </Row>
        <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@3jusaj`}
          columns={this.getColumns()}
          dataSource={fileList}
          pagination={false}
          rowSelection={this.getRowSelection()}
        />
      </div>
    );
  }
  onOperatesClick = (record, index, operate, flag) => {
    const { versionid, id, fileid } = record;
    flag === '0' && window.openFullWindowForXtable(`/spa/document/index2file.jsp?id=${id}&imagefileId=${fileid}&versionid=${versionid}&router=1`
      + `&${window.__moudleParams}#/main/document/fileView`);
    flag === '1' && open(`/weaver/weaver.file.FileDownload?fileid=${fileid}`
      + `&download=1${window.__moudleParams}`);
    if (flag === '2') {
      const { docDetailFormStore } = this.props;
      docDetailFormStore.searchFileVersion({ docid: id, imagefileid: fileid, versionid, isEdit: '1', docImageFileId: record.docImageFileId });
      this.setState({ versionVisible: true, editionRecord: record });
    }
  }
   // 附件操作
   onCancelVersion = () => this.setState({ versionVisible: false })
   onOperatesClickVersion = (record, index, operate, flag) => {
    const { docDetailFormStore } = this.props;
    flag === '0' && open(`/weaver/weaver.file.FileDownload?fileid=${record.imagefileid}`
      + `&download=1${window.__moudleParams}`);
    flag === '1' && Modal.confirm({
      title: getLabel(127574, '确定删除吗？'),
      onOk: () => {
        docDetailFormStore.deleteFileEdition({
          fileid: record.imagefileid,
          id: record.id,
        }, () => {
          const { editionRecord: { id, secid, fileid, versionid, docImageFileId } } = this.state;
           docDetailFormStore.searchFileVersion({ docid: id, imagefileid: fileid, versionid, isEdit: '1', docImageFileId, isdelete: 'true' });
           docDetailFormStore.getFileList({ id, secid });
           if (record.versionCounts == '1') {
            this.setState({ versionVisible: false });
           }
        });
      },
    });
  }
   getFileVersion() {
    const { docDetailFormStore } = this.props,
{ fileVersionTableStore } = docDetailFormStore;
    const { versionVisible } = this.state;
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@g18jx9`}
        icon="icon-coms-doc"
        iconBgcolor="#f14a2d"
        title={getLabel(19587, '版本信息')}
        style={{ width: 800 }}
        maskClosable={false}
        visible={versionVisible}
        onCancel={this.onCancelVersion}
        buttons={[
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@nnx6m6@fileVersion-dialog-close`}
            type="ghost"
            onClick={this.onCancelVersion}
          >{getLabel(309, '关闭')}</Button>,
        ]}
      >
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@920e22`} scrollId="wea_doc_detail_content_file_version" height="100%">
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@g6ku3i`}
            comsWeaTableStore={fileVersionTableStore}
            onOperatesClick={this.onOperatesClickVersion}
          />
        </WeaNewScroll>
      </WeaDialog>
    );
  }
  getColumns() {
    const { id, officeType } = this.state;
    const { docDetailFormStore } = this.props,
{ fileList, setMainImagefile, mainfileLocal } = docDetailFormStore;
    const columns = [{
      title: getLabel(23752, '附件名称'),
      dataIndex: 'filename',
      key: 'filename',
      render: (text, record, index) => (
          <DataListItem ecId={this && this.props && this.props.ecId || ''} record={record} text={text} index={index} onOperatesClick={this.onOperatesClick} />
        ),
    }, {
      title: getLabel(19998, '附件大小'),
      dataIndex: 'filesize',
      key: 'filesize',
    }];
    if (!(officeType == '.docx' || officeType == '.doc' || officeType == '.wps' || officeType == '.xls' || officeType == '.xlsx')) {
      columns.push({
        title: getLabel(514544, '主附件'),
        dataIndex: 'filename',
        key: 'filename',
        render: (text, record, index) => {
          const { ReadOnline } = record;
          return (
            ReadOnline == '1' &&
            <DataListItem ecId={this && this.props && this.props.ecId || ''} record={record} text={text} index={index} dataListItemKey="mainFile" />
          );
        },
      });
    }
    id && columns.push({
      title: '',
      dataIndex: 'ops',
      key: 'ops',
      width: 80,
      className: 'wea-table-operates',
      render: (text, record, index) => (
          <DataListItem
            ecId={this && this.props && this.props.ecId || ''}
            record={record}
            text={text}
            index={index}
            dataListItemKey="opsMenu"
            doDelete={this.doDelete}
            onOperatesClick={this.onOperatesClick}
          />
        ),
    });
    return columns;
  }
  onChangeRowSelection = (sRowKeys, selectedRows) => {
    this.setState({ selectedRowKeys: sRowKeys, selectedRows });
  }
  getRowSelection = () => {
    const { selectedRowKeys } = this.state;
    return {
      selectedRowKeys,
      onChange: this.onChangeRowSelection,
    };
  }
  doDelete = (fileid) => {
    const { docDetailFormStore } = this.props;
    let fileList = toJS(docDetailFormStore.fileList);
    const { selectedRows } = this.state;
    const selectedids = selectedRows.map(item => item.fileid);
	    	 const newFileList = typeof fileid === 'number' || typeof fileid === 'string'
		      ? fileList.filter(item => String(item.fileid) !== String(fileid))
		      : fileList.filter(item => selectedids.indexOf(item.fileid) < 0);
		    docDetailFormStore.updateFileList(newFileList);
    this.setState({ selectedRowKeys: [], selectedRows: [] });
    let flag = true;
    newFileList.forEach((val) => {
      if (docDetailFormStore.mainImagefile == val.fileid) {
        flag = false;
      }
    });
    if (flag && !docDetailFormStore.isAdd) {
      // docDetailFormStore.setDatas({mainfileLocal:""});
    }
  }
  addShare = () => {
    const { id } = this.state;
    const { docDetailFormStore } = this.props;
    this.setState({ shareAddVisible: true });
    docDetailFormStore.getAddShare({ docid: id });
  }
  getShare() {
    const { docDetailFormStore } = this.props,
      { shareTableStore } = docDetailFormStore;
    let shareAddEditBtn = toJS(docDetailFormStore.shareAddEditBtn);
    const { id } = this.state;
    const hasAddBtn = shareAddEditBtn.hasAddBtn === '1';
    const hasDelBtn = shareAddEditBtn.hasDelBtn === '1';
    return (
      <div className="wea-table-edit">
        <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@nfn1zq`} className="wea-table-edit-title" >
          <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@bd2rjr`}>
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ltjrh1`}
              style={{ width: 22 }}
              type="primary"
              title={getLabel(91, '删除')}
              size="small"
              disabled={!hasDelBtn || !`${toJS(shareTableStore.selectedRowKeys).length === 0}`}
              onClick={this.doShareAddDelete}
            ><span className="icon-coms-form-delete-hot" /></Button>
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1y6gdm`}
              style={{ width: 22 }}
              type="primary"
              title={getLabel(1421, '新增')}
              size="small"
              disabled={!hasAddBtn}
              onClick={this.addShare}
            ><span className="icon-coms-Add-to-hot" /></Button>
          </Col>
        </Row>
        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@ntgaf3`}
          comsWeaTableStore={shareTableStore}
        />
      </div>
    );
  }
  onCancelShare = () => this.setState({ shareAddVisible: false })
  onOkShare = (v) => {
    const { docDetailFormStore } = this.props;
    const { id } = this.state;
    docDetailFormStore.doShareAddSubmit({ ...v, id });
    this.setState({ shareAddVisible: false });
  }
  // 添加共享
  getShareAddModal() {
    const { docDetailFormStore } = this.props;
    const { shareAddVisible } = this.state;
    let conditions = toJS(docDetailFormStore.conditions);
    if (conditions.length === 0) {
      return null;
    }
    return (
      <WeaAuth ecId={`${this && this.props && this.props.ecId || ''}_WeaAuth@7lnssl`}
        title={getLabel(18645, '添加共享')}
        visible={shareAddVisible}
        conditions={conditions}
        onOk={this.onOkShare}
        onCancel={this.onCancelShare}
      />
    );
  }
  doShareAddDelete() {
    const { docDetailFormStore } = this.props,
      { shareTableStore } = docDetailFormStore;
    const { id } = this.state;
    docDetailFormStore.deleteShare({ docid: id, shareId: `${toJS(shareTableStore.selectedRowKeys).join()}` });
  }
  backToE8 = () => {
    const { id, secid } = this.state;
    const url = id ? `/docs/docs/DocEdit.jsp?id=${id}`
      : `/docs/docs/DocAdd.jsp?secid=${secid}`;
    window.location.href = url;
  }
  getE8Button() {
    return (
      <BackToE8 ecId={`${this && this.props && this.props.ecId || ''}_BackToE8@226ry0`}
        onClick={this.backToE8}
      />
    );
  }
  onUploadingBtm = (status) => {
    this.setState({ richTextUploadStatus: status });
  }
  setBasic=(v) => {
    const { docDetailFormStore } = this.props;
    docDetailFormStore.setBasic({ docSubject: v });
  }
  setReplyKey = (v) => {
    const { docDetailFormStore } = this.props;
    docDetailFormStore.setReplyKey({ replyremind: v });
  }
  onStatusChange = s => this.setState({ status: s })
  render() {
    const { docDetailFormStore } = this.props;
    const { loading, tabKey, docSubject, doccontent, canShowBJCA, reply: { replyable, replyremind } } = docDetailFormStore;
    let footConfig = toJS(docDetailFormStore.footConfig);
    const { richHeight, isOffice, requestDoc, requestDocSubject, id, secid, showWarm } = this.state;
    const onlyUrl4Content = window.__onlyUrl4Content;
    const preContent = onlyUrl4Content ? window.__preContent : $('.wea-doc-detail-content-main').html() || window.__preContent || '';
    if (window.location.pathname.indexOf('/spa/document/') >= 0) {
      document.title = this.state.id ? getLabel(386301, '文档编辑') : getLabel(1986, '新建文档');
    }
    let bottomBarConfig = [];
    Array.isArray(footConfig) > 0 && footConfig.forEach((item) => {
      bottomBarConfig.push({
        ...item,
        onUploading: this.onUploadingBtm,
        show: item.name !== 'Upload' || item.maxUploadSize != '0' ?
          <span className="wea-doc-add-rich-btm-item"
            title={item.name == 'Upload' ? (`${getLabel(17616, '附件上传')}(${getLabel(385926, '最大{max}M/个').replace('{max}', item.maxUploadSize)})`) : item.title}
          ><i className={item.show} />{item.title}</span> : null,
      });
    });


    let toolbar = [['Source', '-', 'DocProps',
                            '-', 'NewPage', 'Preview', 'Print',
                            '-', 'Bold', 'Italic', 'Underline', 'Strike',
                            'Format', 'Font', 'FontSize', 'lineheight',
                            'TextColor', 'BGColor',
                            '-', 'Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord',
                            '-', 'Undo', 'Redo',
                            '-', 'NumberedList', 'BulletedList', '-',
                            '-', 'Outdent', 'Indent', 'textindent',
                            '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock',
                            '-', 'CopyFormatting', 'RemoveFormat',
                            '-', 'Find', 'Replace', 'SelectAll',
                            '-', 'Link', 'Unlink', 'Anchor',
                            '-', 'Maximize',
                            '-', 'Html5video', 'Table', 'HorizontalRule', 'Smiley', 'Image',
                            'SpecialChar', 'PageBreak', 'Iframe',
                          ]];

    	if (navigator.userAgent.indexOf('MSIE 9.0') > -1) {
    				toolbar = [
				            { name: 'document', items: ['Source'] },
				            { name: 'paragraph', items: ['DocProps', '-', 'NewPage', 'Preview', 'Print', '-', 'Outdent', 'Indent', 'textindent', '-', 'Bold', 'Italic', 'Underline', 'Strike'] },
				            { name: 'styles', items: ['Format', 'Font', 'FontSize', 'lineheight'] },
				            { name: 'colors', items: ['TextColor', 'BGColor'] },
				            { name: 'operate', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] },
				            { name: 'ligroup', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent'] },
				            { name: 'textalign', items: ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] },
				            { name: 'brush', items: ['CopyFormatting', 'RemoveFormat', '-', 'Find', 'Replace', 'SelectAll'] },
				            { name: 'alink', items: ['Link', 'Unlink', 'Anchor'] },
				            { name: 'insert', items: ['Image', 'Html5video', 'Table', 'HorizontalRule', 'Smiley', 'SpecialChar', 'PageBreak', 'Iframe', 'Maximize'] },
				        ];
       }
    let rightMenuDisabled = false;
    if (tabKey == '0' && requestDoc == '1') {
      rightMenuDisabled = true;
    }
    return (
      <div className={`wea-doc-detail wea-doc-add ${requestDoc === '1' ? 'wea-odoc-add' : ''}`}>
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@pyl5c7`} datas={this.getRightMenu()} disabled={rightMenuDisabled}>
          <WeaReqTop ecId={`${this && this.props && this.props.ecId || ''}_WeaReqTop@fl88m6`}
            title={<span style={{ marginLeft: 8 }}>
              <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@naltlj`}
                placeholder={getLabel(130030, '文档标题')}
                value={docSubject}
                style={{ width: 455, display: requestDoc === '1' ? '' : '' }}
                viewAttr={requestDoc === '1' ? '3' : '3'}
                onChange={this.setBasic}
              />
              {
                replyable === '1' && requestDoc !== '1' &&
                <div style={{ display: 'inline' }}>
                    <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@43o84x`}
                      style={{ position: 'relative', bottom: '5px', left: '30px' }}
                      id="replycheck"
                      value={replyremind}
                      onChange={this.setReplyKey}
                    />
                    <span
                      style={{ position: 'relative', left: '34px', bottom: '4px' }}
                    >{getLabel(18641, '回复提醒')}</span>
                    <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@ss4nio`}
                      style={{ position: 'relative', left: '39px', bottom: '5px' }}
                        // width =  {120} //如果要自定义宽度，在这里设置
                      title={getLabel(515194, '只对文档所有者提醒')}
                      isCenter={true}
                    />
                  </div>
              }

            </span>}
            loading={loading}
            icon={<i className="icon-coms-doc" />}
            iconBgcolor="#df583a"
            replaceTab={
              <Tabs ecId={`${this && this.props && this.props.ecId || ''}_Tabs@yqm1q3`}
                activeKey={tabKey}
                onChange={this.onTabsChange}
              >
                { this.getTabPane() }
              </Tabs>
            }
            buttons={this.getButtons()}
            showDropIcon
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
          >
            <div className="wea-doc-detail-content"
              style={isOffice && tabKey === '0' ? { padding: 0 } : {}}
            >
              <div className="wea-doc-detail-content-inner" style={{ overflow: 'hidden' }}>
                {
                  (isOffice || canShowBJCA)
                  ?
                  (!onlyUrl4Content ? <div className="wea-doc-detail-content-main"
                    style={tabKey === '0' && !showWarm ? { display: 'block' } : { height: '1px', marginTop: '-1px' }}
                    dangerouslySetInnerHTML={{ __html: preContent }}
                  /> :
                  <div className="wea-doc-detail-content-main"
                    style={tabKey === '0' && !showWarm ? { display: 'block' } : { height: '1px', marginTop: '-1px' }}
                  >
                        <iframe id="webOffice" src={preContent} style={{ display: 'block', width: '100%', height: '100%', border: 0 }} />
                  </div>)
                  :
                  <div style={{ display: tabKey === '0' ? 'block' : 'none' }}>
                    { richHeight ?
                      <WeaRichText ecId={`${this && this.props && this.props.ecId || ''}_WeaRichText@z5vrtg`}
                        ref="doc_add"
                        value={toJS(docDetailFormStore.doccontent)}
                        ckConfig={{
                          toolbar,
                          height: richHeight,
                          uploadUrl: '/api/doc/upload/uploadFile',
                          fullPage: true,
                          fullPageContentsCss: '',
                          extraPlugins: 'image2,lineheight,docprops,html5video,'
                            + 'widget,widgetselection,clipboard,lineutils',
                        }}
                        // extentsConfig={this.getExtentsConfig()}
                        bottomBarConfig={bottomBarConfig}
                        onStatusChange={this.onStatusChange}
                        onToolsChange={this.onToolsChange}
                        // onSave={v => console.log('save0: ', v)}
                      /> : null
                    }
                  </div>
                }
                <div style={{ display: tabKey === '1' ? 'block' : 'none', height: '100%' }}>
                  <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@swr3qi`} height={'100%'}>
                  	{ this.getAttr() }
                  </WeaNewScroll>
                </div>
                <div style={{ display: tabKey === '2' ? 'block' : 'none', height: '100%' }}>
                  <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@pj8h1o`} height={'100%'}>
                    { this.getFileUpload() }
                  </WeaNewScroll>
                </div>
                <div style={{ display: tabKey === '3' ? 'block' : 'none', height: '100%' }}>
                  <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@we0m75`} height={'100%'}>
                    { this.getShare() }
                  </WeaNewScroll>
                </div>
                { this.getShareAddModal() }
              </div>
            </div>
          </WeaReqTop>
        </WeaRightMenu>
        { this.getFileVersion() }
        <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@wwzhsk`} pathname="/document/edit" secid={secid} docid={id} />
      </div>
    );
  }
}

// 组件检错机制
DetailForm = WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@2ed6za`} msg={props.error || getLabel(385218, '对不起，该页面异常，请联系管理员！')} />, { error: '' })(DetailForm);


export default DetailForm;
